package com.duolai.bean;

import com.spring.annotation.Component;
import com.spring.annotation.DuolaiValue;
import com.spring.interfaces.BeanPostProcessor;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @program: duolai-spring-01
 * @description: 自定义后置处理器
 * @author: chaidl  ！
 * @create: 2021-09-05 16:11
 */
@Component
public class DuoLaiValueBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        //拿到当前对象的所有字段，判断是不是有@DuolaiValue注解，如果有的话，就属性赋值
        for (Field field : bean.getClass().getDeclaredFields()) {
            if (field.isAnnotationPresent(DuolaiValue.class)){
                field.setAccessible(true);
                try {
                    System.out.println("前置处理器");
                    field.set(bean,field.getAnnotation(DuolaiValue.class).value());
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return bean;
    }
}
